from rest_framework import serializers
from . import models


class UserModelSerializer(serializers.ModelSerializer):
    #字段声明
    sms_code=serializers.CharField(min_length=4,max_length=6,required=True,write_only=True,help_text='短信验证码')
    token=serializers.CharField(read_only=True,help_text='jwt认证的token')
    '''
    用户注册的序列化器
    '''
    #模型相关的声明
    class Meta:
        model=models.User
        fields=['mobile','sms_code','password','token','username','id']
        #给模型序列器额外的声明
        extra_kwargs={
            'passowrd':{'min_length':6,"write_only":True},
            'mobile':{'write_only':True},
            'username':{'read_only':True}
        }

    def validate_mobile(self,data):
        '''
        验证手机号码
        :return:
        '''
        #检查手机号格式
        import re
        ret=re.match('1[3-9]\d{9}',data)
        if not ret:
            raise serializers.ValidationError('手机号格式错误')
        #是否被注册
        try:
            models.User.objects.get(mobile=data)
            raise serializers.ValidationError('该手机号已经注册,请直接登录')
        except models.User.DoesNotExist:
            pass
        return data

    #验证数据
    def validate(self, attrs):

        mobile=attrs.get('mobile')
        client_sms_code=attrs.get('sms_code')
        return attrs

    #创建数据的方法
    def create(self,validated_data):
        '''
        创建数据
        :param validated_data:
        :return:
        '''
        mobile=validated_data.get("mobile")
        password=validated_data.get("password")
        try:
            user=models.User.objects.create_user(username=mobile,password=password,mobile=mobile)
            # 手动生成jwt
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            user.token = jwt_encode_handler(payload)
            return user
        except:
            raise serializers.ValidationError('保存用户失败')